<?php

namespace Acme\FirmsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\FirmsBundle\Entity\Firms;
use Acme\FirmsBundle\Form\AdminFirmsForm;
use Acme\FirmsBundle\lib\AdminConfigJqGrid;
use Acme\FirmsBundle\lib\AdminCategoryConfigJqGrid;
/**
 * Firms controller.
 *
 * @Route("/admin/admin_firms")
 */
class AdminController extends Controller
{
    /**
     * Lists all Firms entities.
     *
     * @Route("/", name="admin_firms")
     * @Template()
     */
    public function indexAction() {
      $em = $this->getDoctrine()->getEntityManager();
      $adconfig = new AdminConfigJqGrid(array('EntityManager' => $em,
                                              'Repository' => 'AcmeFirmsBundle:Firms'));
      $adconfig->getJqGrid()->findByKey('url')
               ->setValue($this->generateUrl('admin_get_firms'));
      $adconfig->getJqGrid()->findByKey('editurl')
                            ->setValue($this->generateUrl('admin_del_firms'));
    
      return array('params' => $adconfig->getJqGrid()->getProperties());
    }
    
    /**
     *
     * @Route("/get_firms", name="admin_get_firms") 
     */
    public function get_firmsAction(\Symfony\Component\HttpFoundation\Request $request) {
      if ($request->isXmlHttpRequest()) {
        $em = $this->getDoctrine()->getEntityManager();
        $adconfig = new AdminConfigJqGrid(array('EntityManager' => $em,
                                              'Repository'    => 'AcmeFirmsBundle:Firms'));
        $adconfig->getJqGrid()->findByKey('url')
                ->setValue($this->generateUrl('admin_get_firms'));
        $adconfig->getJqGrid()->findByKey('editurl')
                              ->setValue($this->generateUrl('admin_del_firms'));
        $gj = new \Alex616\jqGridBundle\lib\GeneratorJqGrid($adconfig);
        $results = $gj->getResults($request, 'p');
        $response = new \Symfony\Component\HttpFoundation\Response($results, 200, array('Content-Type' => 'application/json'));
        return $response;
      }
      return new \Symfony\Component\HttpFoundation\Response('', 404);
    }

    /**
     * Displays a form to create a new Firms entity.
     *
     * @Route("/new", name="admin_firms_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Firms();
        $form   = $this->createForm(new AdminFirmsForm(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Creates a new Firms entity.
     *
     * @Route("/create", name="admin_firms_create")
     * @Method("post")
     * @Template("AcmeFirmsBundle:Firms:new.html.twig")
     */
    public function createAction()
    {
        $entity  = new Firms();
        $request = $this->getRequest();
        $form    = $this->createForm(new AdminFirmsForm(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_firms_show', array('id' => $entity->getId())));
            
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Displays a form to edit an existing Firms entity.
     *
     * @Route("/{id}/edit", name="admin_firms_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeFirmsBundle:Firms')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Firms entity.');
        }

        $editForm = $this->createForm(new AdminFirmsForm(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Firms entity.
     *
     * @Route("/{id}/update", name="admin_firms_update")
     * @Method("post")
     * @Template("AcmeFirmsBundle:Firms:edit.html.twig")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeFirmsBundle:Firms')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Firms entity.');
        }

        $editForm   = $this->createForm(new AdminFirmsForm(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_firms_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Firms entity.
     *
     * @Route("/{id}/delete", name="admin_firms_delete")
     * @Method("post")
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('AcmeFirmsBundle:Firms')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Firms entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_firms'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
   /**
   * @Route("/del_firms", name="admin_del_firms")
   * 
   */
  public function deleteFirmsAction(\Symfony\Component\HttpFoundation\Request $request) {
    if ( $request->isXmlHttpRequest() ) {
      $em = $this->getDoctrine()->getEntityManager();
      $adconfig = new AdminConfigJqGrid(array('EntityManager' => $em,
                                              'Repository'    => 'AcmeFirmsBundle:Firms'));
      $adconfig->getJqGrid()->findByKey('url')
              ->setValue($this->generateUrl('admin_get_firms'));
      $adconfig->getJqGrid()->findByKey('editurl')
                            ->setValue($this->generateUrl('admin_del_firms'));
      $gj = new \Alex616\jqGridBundle\lib\GeneratorJqGrid($adconfig);
      $gj->removeObjects($request);
    }
    return new \Symfony\Component\HttpFoundation\Response('', 200);
  }
  
  /**
   * Lists all CategoryFirms entities.
   *
    * @Route("/category", name="admin_category")
   * @Template()
   */
  public function categoryAction() {
    $em = $this->getDoctrine()->getEntityManager();
    $adconfig = new AdminCategoryConfigJqGrid(array('EntityManager' => $em,
                'Repository' => 'AcmeFirmsBundle:CategoryFirms'));
    $adconfig->getJqGrid()->findByKey('url')
            ->setValue($this->generateUrl('admin_get_category'));
    $adconfig->getJqGrid()->findByKey('editurl')
            ->setValue($this->generateUrl('admin_action_category'));

    return array('params' => $adconfig->getJqGrid()->getProperties());
  }

  /**
   *
   * @Route("/get_category", name="admin_get_category") 
   */
  public function get_categoryAction(\Symfony\Component\HttpFoundation\Request $request) {
    if ($request->isXmlHttpRequest()) {
      $em = $this->getDoctrine()->getEntityManager();
      $adconfig = new AdminCategoryConfigJqGrid(array('EntityManager' => $em,
                  'Repository' => 'AcmeFirmsBundle:CategoryFirms'));
      $adconfig->getJqGrid()->findByKey('url')
              ->setValue($this->generateUrl('admin_get_category'));
      $adconfig->getJqGrid()->findByKey('editurl')
              ->setValue($this->generateUrl('admin_action_category'));
      $gj = new \Alex616\jqGridBundle\lib\GeneratorJqGrid($adconfig);
      $results = $gj->getResults($request, 'p');
      $response = new \Symfony\Component\HttpFoundation\Response($results, 200, array('Content-Type' => 'application/json'));
      return $response;
    }
    return new \Symfony\Component\HttpFoundation\Response('', 404);
  }

  

  /**
   * @Route("/action_category", name="admin_action_category")
   * 
   */
  public function actionCategoryAction(\Symfony\Component\HttpFoundation\Request $request) {
    if ($request->isXmlHttpRequest()) {
      $oper = $request->get('oper');
      $id = $request->get('id');
      $em = $this->getDoctrine()->getEntityManager();
      switch ($oper) {
        case 'edit':
          $category = $em->getRepository('AcmeFirmsBundle:CategoryFirms')->find($id);
          $category->setName($request->get('name'));
          $em->persist($category);
          break;
        case 'del':
          $ids = explode(',', $id);
          $repository = $em->getRepository('AcmeFirmsBundle:CategoryFirms');
          if (count($ids) > 1){
            $qb = $repository->createQueryBuilder('cf');
            $categoryes = $qb ->where($qb->expr()->in('cf.id', '?1'))
                              ->setParameters(array(1 => $ids))
                              ->getQuery()->getResult();
            foreach($categoryes as $category) {
              $em->remove($category);
            }
          } 
          else {
            $category = $repository->find($ids[0]);
            $em->remove($category);
          }
          break;
        case 'add':
          $category = new \Acme\FirmsBundle\Entity\CategoryFirms();
          $category->setName($request->get('name'));
          $em->persist($category);
          break;
        default:
          break;
      }
      $em->flush();
    }
    return new \Symfony\Component\HttpFoundation\Response('', 200);
  }
}
